import {
    defineStore
} from "pinia"
import {
    getAllLayerdata,
    getFirstDatas,
    getSceneLayerData,
    getSceneLayerList
} from '../api/system.js'

import * as tileStore from "../api/tileStore";

import {
    addLayer,
    getLayers,
    getLayerByAttr,
    removeLayer,
    translate
} from "../../static/CIM/BQGIS-load";


export const useLayerStore = defineStore("layerStore", { //添加了export
    state: () => {
        return {
            treeData: [],
            checkedKeys: [],
            layerList: [],
            maxImageSort: 0
        }
    },
    actions: {
        async getlayerList(option) {
            return await getAllLayerdata(option)
        },
        async getFirstData() {
            return await getFirstDatas()
        },
        async setTreeData() {
            this.treeData = await getSceneLayerData()
            return this.treeData
        },
        // 加载图层
        loadLayers(viewer, option) {
            const layer = getLayerByAttr(viewer, option)
            if (layer) {
                if (option.type === '影像') {
                    layer.zIndex = -option.sort
                }
                layer.show = true
            } else {
                const data = this.format(option)
                const sceneId = window.sessionStorage.getItem("sceneId")
                if (!sceneId || data.typecategory.indexOf("3dtiles") === -1) {
                    addLayer(viewer, data);
                } else {
                    const param = tileStore.get(option.id)
                    console.log(param, 'param')
                    addLayer(viewer, Object.assign(data, param));
                }
            }
        },
        // 隐藏图层
        hiddenLayers(viewer, data) {
            const layer = getLayerByAttr(viewer, data);
            if (layer) {
                layer.show = false;
            }
        },
        updataLayer(viewer, option) {
            removeLayer(viewer, option)
            loadLayers(viewer, option)
        },
        setCheckedKeys(val) {
            this.checkedKeys = val
        },
        addCheckedKeys(id) {
            const index = this.checkedKeys.indexOf(id);
            if (index === -1) {
                this.checkedKeys.push(id)
            }
        },
        delCheckedKeys(id) {
            const index = this.checkedKeys.indexOf(id);
            if (index !== -1) {
                this.checkedKeys.splice(index, 1)
            }
        },
        // 获取图层树
        async getTreeData(viewer = window.viewer, sceneId) {
            return getSceneLayerData(sceneId).then(res => {
                this.setLayerData(res)
                return this.treeData
            })
        },
        // 获取场景图层树(在场景页面使用该接口)
        async getSceneTreeDataDoNotLoad(viewer = window.viewer, sceneId) {
            if (sceneId) {
                return getSceneLayerList(sceneId).then(res => {
                    this.treeData = res
                })
            } else {
                return Promise.reject()
            }
        },
        // 获取场景图层树,并设置checkedKeys与layerList(在场景页面使用该接口)
        async getSceneTreeData(viewer = window.viewer, sceneId) {
            if (sceneId) {
                return getSceneLayerList(sceneId).then(res => {
                    this.setLayerData(res)
                    return this.treeData
                })
            } else {
                return Promise.reject()
            }
        },
        setLayerData(treeData) {
            this.treeData = treeData
            this.checkedKeys = []
            this.layerList = []
            const recursion = (data) => {
                return data.forEach(item => {
                    if (item.children) {
                        recursion(item.children)
                    } else {
                        if (item.checked) {
                            if (item.type === '影像') {
                                this.maxImageSort = this.maxImageSort > item.sort ? this.maxImageSort : item.sort
                            }
                            this.checkedKeys.push(item.id)
                            this.layerList.push(item)
                        }
                    }
                })
            }
            recursion(treeData)
        },
        // 加载图层树
        loadTreeData(viewer = window.viewer) {
            const layers = getLayers(viewer)
            layers.forEach(layer => {
                layer.show = false
            })
            this.layerList.forEach(item => {
                this.loadLayers(viewer, item)
            })
        },
        format(data) {
            const obj = {}
            for (let key in data) {
                obj[key.toLowerCase()] = data[key]
            }
            if (obj) {
                obj.url = obj.data;
                obj.category = obj.type
                if (obj.type === "影像") {
                    obj.zIndex = -obj.sort
                    obj.type = obj.typecategory
                    if (['baidu' , 'tencent'].indexOf(obj.typecategory) != -1 && obj.layer && obj.layer.indexOf('custom') != -1) {
                        [obj.layer, obj.style] = obj.layer.split('_')
                    }
                } else if (obj.type === '高程') {
                    obj.type = "terrain";
                    obj.terrain = {
                        url: obj.data,
                        type: obj.typecategory
                    };
                } else if (obj.type === '模型') {
                    this.formatModel(obj)
                } else if (obj.type === '全景图') {
                    this.formatPano(obj)
                } else {
                    obj.type = obj.typecategory
                }
            }
            return obj
        },
        formatModel(obj) {
            if (!obj.json) return
            try {
                const parmes = typeof obj.json === 'object' ? obj.json : JSON.parse(obj.json)
                obj.position = parmes.position
                if (obj.typecategory.indexOf("3dtiles") !== -1) {
                    obj.rotation = parmes.rotation
                    if (parmes.loadConfig) {
                        obj = Object.assign(obj, parmes.loadConfig)
                    }
                } else if (obj.typecategory == 'gltf' || obj.typecategory == 'obj') {
                    obj.heading = parmes.heading
                    obj.pitch = parmes.pitch
                    obj.roll = parmes.roll
                }
            } catch (err) {
                console.error(err) // json字符串解析失败
            }
        },
        formatPano(obj) {
            if (!obj.json) return
            try {
                const parmes = typeof obj.json === 'object' ? obj.json : JSON.parse(obj.json)
                obj.position = parmes.position
            } catch (err) {
                console.error(err) // json字符串解析失败
            }
        }
    }
})